<template>
  <section class="content clear">
    <section class="content-search">
      <el-button size="mini" type="primary" @click="addRole">新增岗位</el-button>
    </section>
    <section class="content-list">
      <el-table :data="tableData" stripe style="width: 100%">
        <el-table-column type="index" label="序号" width="80"></el-table-column>
        <el-table-column prop="id" label="岗位ID" width="80"></el-table-column>
        <el-table-column prop="name" label="岗位名称">
          <template slot-scope="scope">
            <span v-if="!scope.row.type">{{scope.row.name}}</span>
            <el-input v-if="scope.row.type" size="mini" v-model="scope.row.name" placeholder="请输入岗位名称"></el-input>
          </template>
        </el-table-column>
        <!--<el-table-column prop="apps" show-overflow-tooltip label="授权应用">
          <template slot-scope="scope">
            {{scope.row.apps | toList}}
          </template>
        </el-table-column>-->
        <el-table-column prop="createTime" show-overflow-tooltip label="创建时间" width="200">
          <template slot-scope="scope">
            {{scope.row.createTime | moment("YYYY-MM-DD HH:mm:ss")}}
          </template>
        </el-table-column>
        <el-table-column prop="valid" show-overflow-tooltip label="状态">
          <template slot-scope="scope">
            <span v-if="scope.row.valid === 1 && scope.row.id">正常</span>
            <span class="text-error" v-if="scope.row.valid !== 1 && scope.row.id">已冻结</span>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button v-if="scope.row.id" @click="checkList(scope.row.id)" type="text" size="mini">查看名单</el-button>
            <el-button v-if="!scope.row.type && scope.row.id" :disabled="scope.row.createTime === null" @click="updateRole(scope.row)" type="text" size="mini">修改</el-button>
            <el-button v-if="scope.row.type" @click="saveRole(scope.row)" type="text" size="mini">保存</el-button>
            <!--<el-button v-if="scope.row.valid === 1 && scope.row.id" @click="freezeRole(scope.row)" type="text" size="mini">冻结</el-button>-->
            <!--<el-button v-if="scope.row.valid !== 1 && scope.row.id" @click="thawRole(scope.row)" type="text" size="mini">解冻</el-button>-->
            <el-button  type="text" @click="deleteJob(scope.row.id)" plain size="mini" class="delete-btn">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </section>
    <el-dialog title="授权" :visible.sync="dialogGrant">
      <div style="text-align: center">
        <el-transfer style="text-align: left; display: inline-block" v-model="selected" filterable :titles="['未授权应用', '授权应用']" :button-texts="['加入左侧', '加入右侧']" :format="{
            noChecked: '${total}',
            hasChecked: '${checked}/${total}'
          }" :data="data">
        </el-transfer>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogGrant = false">取 消</el-button>
        <el-button type="primary" @click="confirm">确 定</el-button>
      </div>
    </el-dialog>
  </section>
</template>

<script>
import { role } from '@/api/index'
export default {
  name: 'role',
  data () {
    return {
      tableData: [],
      dialogGrant: false,
      temRole: '',
      data: [],
      selected: []
    }
  },
  created () {
    this.getRoleList()
  },
  filters: {
    toList (val) {
      let temp = []
      val.forEach((item) => {
        temp.push(item.name)
      })
      return temp.join('、')
    }
  },
  methods: {
    getRoleList () {
      role()._getRoleList().then((res) => {
        this.tableData.length = 0
        for (let i = 0; i < res.data.length; i++) {
          this.tableData.push({
            id: res.data[i].id,
            valid: res.data[i].valid,
            name: res.data[i].name,
            createTime: res.data[i].createTime,
            apps: res.data[i].apps,
            type: false
          })
        }
      })
    },
    checkList (val) {
      this.$emit('check', val)
    },
    checkType () {
      let tag = false
      this.tableData.some((item) => {
        if (item.type) {
          tag = true
        }
      })
      return tag
    },
    addRole () {
      if (this.checkType()) {
        this.$message.error('请先保存')
      } else {
        this.tableData.push({
          valid: '',
          name: '',
          createTime: '',
          apps: [],
          type: true
        })
      }
    },
    updateRole (val) {
      if (this.checkType()) {
        this.$message.error('请先保存')
      } else {
        val.type = true
      }
    },
    checkSpecificKey (str) {
      var specialKey = '[`~!@#$^&*%()=|{}\':;\',\\\\[\\\\].<>/?~！#￥……&*（）——|{}【】‘；：""”“\'。，、？]‘\''
      for (var i = 0; i < str.length; i++) {
        if (specialKey.indexOf(str.substr(i, 1)) !== -1) {
          this.$message.error('不能出现特殊字符')
          return false
        }
      }
      return true
    },
    saveRole (val) {
      if (this.checkSpecificKey(val.name)) {
        if (val.id) {
          let req = {
            id: val.id,
            name: val.name
          }
          role()._editRole(req).then((res) => {
            if (res.status) {
              this.$message.success('修改岗位成功')
              this.getRoleList()
            } else {
              this.$message.error(res.message)
            }
          })
        } else {
          let req = {
            name: val.name
          }
          role()._addRole(req).then((res) => {
            if (res.status) {
              this.$message.success('新增岗位成功')
              this.getRoleList()
            } else {
              this.$message.error(res.message)
            }
          })
        }
      }
    },
    freezeRole (val) {
      this.$confirm('此操作将冻结该岗位, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        role()._freezeRole(val.id).then((res) => {
          if (res.status) {
            this.$message.success('冻结岗位成功')
            this.getRoleList()
          } else {
            this.$message.error(res.message)
          }
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消冻结'
        })
      })
    },
    thawRole (val) {
      this.$confirm('此操作将解冻该岗位, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        role()._thawRole(val.id).then((res) => {
          if (res.status) {
            this.$message.success('解冻岗位成功')
            this.getRoleList()
          } else {
            this.$message.error(res.message)
          }
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消冻结'
        })
      })
    },
    deleteJob (id) {
      role()._deleteJob(id).then(res => {
        if (res.status) {
          this.$message.success(res.data)
        } else {
          const msg = res.message ? res.message : '删除失败'
          this.$message.error(msg)
        }
      })
    },
    /*  grantApp (val) {
      this.temRole = val.id
      this.dialogGrant = true
      this.selected.length = 0
      this.getAllApp()
      val.apps.forEach((item) => {
        this.selected.push(item.id)
      })
    }, */
    handleChange (value, direction, movedKeys) {
      console.log(value, direction, movedKeys)
    },
    getAllApp () {
      role()._getAllApp().then((res) => {
        if (res.status) {
          this.data.length = 0
          for (let i = 0; i < res.data.length; i++) {
            this.data.push({
              key: res.data[i].id,
              label: res.data[i].name
            })
          }
        }
      })
    },
    confirm () {
      let req = {
        appIds: this.selected,
        roleId: this.temRole
      }
      role()._grantApp(req).then((res) => {
        if (res.status) {
          this.dialogGrant = false
          this.$message.success('授权应用成功')
          this.getRoleList()
        } else {
          this.$message.error(res.message)
        }
      })
    }
  }
}
</script>
<style>
  .delete-btn{
    color: #ff1111;
  }
</style>
